import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../util/Toast.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/util/BlankToolBarTool.dart';
import 'package:flutter_aygsh/util/LoadingUtil.dart';
import '../util/SignUtil.dart';
import '../liz_mine/set/ArticleDetail.dart';

class RegisterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new RegisterView();
  }
}

TextEditingController codeController = new TextEditingController();
TextEditingController userController = new TextEditingController();
TextEditingController passController = new TextEditingController();
TextEditingController authController = new TextEditingController();

class RegisterView extends State<RegisterPage> {
  bool check = false;
  Timer _countdownTimer;
  int _countdownNum = 59;
  String codeString = "获取验证码";
  int codeStatus = 1;
  BlankToolBarModel barModel = BlankToolBarModel();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    barModel.outSideCallback = focusNodeChange;
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    barModel.removeFocusListeners();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "注册账号",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.1,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.black),
        ),
        body: BlankToolBarTool.blankToolBarWidget(
          context,
          model: barModel,
          body: Container(
              color: white,
              child: new ListView(
                children: <Widget>[
                  new Column(
                    children: <Widget>[
                      loginTopImg(),
                      loginUserEditInput(),
                      new Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0,
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0),
                        child: Divider(
                          height: 1,
                          color: divideColor,
                        ),
                      ),
                      loginUserCodeInput(),
                      new Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0,
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0),
                        child: Divider(
                          height: 1,
                          color: divideColor,
                        ),
                      ),
                      loginPassEditInput(),
                      new Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0,
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0),
                        child: Divider(
                          height: 1,
                          color: divideColor,
                        ),
                      ),
                      loginAuthCodeInput(),
                      new Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0,
                            ScreenUtil.getInstance().setWidth(DP_100),
                            0.0),
                        child: Divider(
                          height: 1,
                          color: divideColor,
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(
                            ScreenUtil.getInstance().setWidth(DP_60),
                            ScreenUtil.getInstance().setWidth(DP_50),
                            ScreenUtil.getInstance().setWidth(DP_60),
                            0.0),
                        child: Row(
                          children: <Widget>[
                            new Checkbox(
                              value: this.check,
                              activeColor: Colors.blue,
                              onChanged: (bool val) {
                                setState(() {
                                  this.check = !this.check;
                                });
                              },
                            ),
                            Text(
                              '阅读并已同意',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE),
                                  color: Colors.black54),
                            ),
                            GestureDetector(
                              onTap: () {
                                Navigator.of(context)
                                    .push(MaterialPageRoute(builder: (context) {
                                  return new ArticleDetailPage(
                                    article_id: '2',
                                  );
                                }));
                              },
                              child: Text(
                                '《用户协议》',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: mainColor),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Navigator.of(context)
                                    .push(MaterialPageRoute(builder: (context) {
                                  return new ArticleDetailPage(
                                    article_id: '14',
                                  );
                                }));
                              },
                              child: Text(
                                '《隐私政策》',
                                style: TextStyle(
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE),
                                    color: mainColor),
                              ),
                            )
                          ],
                        ),
                      ),
                      loginButton(context),
                    ],
                  )
                ],
              )),
        ));
  }

// ignore: missing_function_parameters
  Widget loginTopImg() {
    return new Padding(
      padding: EdgeInsets.all(kMargin15),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(15.0),
        child: new Image.asset(
          'images/logo.png',
        ),
      ),
    );
  }

  Widget loginUserEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          0.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_phone.png",
                  // scale: 1.2,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                keyboardAppearance: Brightness.light,
                cursorColor: mainColor,
                controller: userController,
                decoration: new InputDecoration(
                    hintText: "输入手机号",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       userController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginUserCodeInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_safe.png",
                  // scale: 1.2,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: codeController,
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                decoration: new InputDecoration(
                    hintText: "输入验证码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          new Container(
            width: ScreenUtil.getInstance().setWidth(DP_200),
            height: ScreenUtil.getInstance().setHeight(DP_50),
            margin: EdgeInsets.fromLTRB(0, 0, 0, 8),
            decoration: new BoxDecoration(
                color: codeStatus == 0
                    ? Color.fromARGB(255, 99, 99, 99)
                    : Color.fromARGB(255, 255, 140, 16),
                borderRadius: BorderRadius.circular(20.0)),
            child: new FlatButton(
              child: new Padding(
                padding: EdgeInsets.all(0.0),
                child: new Text(
                  codeString,
                  style: new TextStyle(
                      color: Colors.white,
                      fontSize: ScreenUtil.getInstance().setSp(MINI_FONT_SIZE)),
                ),
              ),
              onPressed: () {
                if (codeStatus == 0) {
                  return;
                }
                if (userController.text.isEmpty) {
                  Toast.toast(context, msg: "请输入手机号");
                  // Fluttertoast.showToast(msg: "请输入手机号");
                  return;
                }
                showDialog(
                    context: context,
                    barrierDismissible: false,
                    builder: (_) {
                      return new NetLoadingDialog(
                        loadingText: "获取中...",
                        bgColor: Color.fromARGB(255, 0, 0, 0),
                        requestCallBack: getPhoneCode(),
                        outsideDismiss: false,
                      );
                    });
              },
            ),
          )
        ],
      ),
    );
  }

  getPhoneCode() async {
    // FormData formData = new FormData.fromMap({
    //   "phone": userController.text,
    // });
    Map map = new Map();
    map['phone'] = userController.text;
    map['sign_type'] = createSignType(Api.URL_SMS_REGISTERCODE);
    Response<String> response =
        await HttpUtil().post(Api.URL_SMS_REGISTERCODE, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    //  Navigator.of(context).pop(1);
    Toast.toast(context, msg: msg);
    print(userMap);
    if (code == 1) {
      setState(() {
        codeStatus = 0;
        if (_countdownTimer != null) {
          return;
        }
        codeString = '${_countdownNum--}重新获取';
        _countdownTimer = new Timer.periodic(new Duration(seconds: 1), (timer) {
          setState(() {
            if (_countdownNum > 0) {
              codeStatus = 0;
              codeString = '${_countdownNum--}重新获取';
            } else {
              codeString = '获取验证码';
              codeStatus = 1;
              _countdownNum = 59;
              _countdownTimer.cancel();
              _countdownTimer = null;
            }
          });
        });
      });
    }
    return true;
  }

  Widget loginPassEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_lock.png",
                  // scale: 1.2,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                keyboardAppearance: Brightness.light,
                controller: passController,
                obscureText: true,
                decoration: new InputDecoration(
                    hintText: "请设置登录密码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
        ],
      ),
    );
  }

  Widget loginAuthCodeInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setWidth(DP_100),
          10.0, ScreenUtil.getInstance().setWidth(DP_100), 0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_safe.png",
                  // scale: 1.2,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                keyboardAppearance: Brightness.light,
                controller: authController,
                decoration: new InputDecoration(
                    hintText: "请填写店主邀请码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
        ],
      ),
    );
  }

  Widget loginButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: ScreenUtil.getInstance().setWidth(DP_90),
      decoration: new BoxDecoration(
          color: Color.fromARGB(255, 255, 140, 16),
          borderRadius: BorderRadius.circular(DP_80)),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            "立即注册",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          _checkSub(context);
        },
      ),
    );
  }

  void toFindPwd() {
    print("找回密码");
  }

  void toRegister() {
    print("用户注册");
  }

  void _checkSub(BuildContext context) {
    print(check);
    if (!check) {
      Toast.toast(context, msg: "请勾选协议");
      return;
    }
    String msgStr = "";
    if (!userController.text.isNotEmpty) {
      msgStr = "请输入手机号";
    } else if (!codeController.text.isNotEmpty) {
      msgStr = "请输入短信验证码";
    } else if (!passController.text.isNotEmpty) {
      msgStr = "请输入登录密码";
    }
    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "注册中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      register();
    }
  }

  register() async {
    String auth = '';
    if (authController.text.length > 6) {
      auth = 'referrer_phone';
    } else {
      auth = 'auth_code';
    }
    Map map = new Map();
    map['phone'] = userController.text;
    map['pwd1'] = passController.text;
    map['pwd2'] = passController.text;
    map['code'] = codeController.text;
    if (authController.text.length > 0) {
      map[auth] = authController.text;
    }
    map['sign_type'] = createSignType(Api.URL_ACCOUNT_REGISTER);
    Response<String> response =
        await HttpUtil().post(Api.URL_ACCOUNT_REGISTER, data: getSign(map));
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Toast.toast(context, msg: msg);
    // Fluttertoast.showToast(msg: msg);
    if (code == 1) {
      Navigator.of(context).pop();
    }
    return true;
  }
}
